package com.Maybe.book.interceptor;

import com.Maybe.book.constants.Constants;
import com.Maybe.book.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;


@Slf4j
@Component
//自定义拦截器
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle目标方法执行前...");
        HttpSession session = request.getSession(false);//false->如果为空，不会创建session对象的
        if(!checkUser(session)){
            response.setContentType("text/html;charset-utf-8");
            response.setStatus(401);//401就是身份未经过认证，相当于未登陆
            String msg="用户未登录";
            response.getOutputStream().write(msg.getBytes(StandardCharsets.UTF_8));
            return false;
        }
        return true;

    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }
    public boolean checkUser(HttpSession session){
        if(session==null||session.getAttribute(Constants.SESSION_USER_KEY)==null){
            log.warn("用户未登陆");
            return false;
        }
        UserInfo userInfo = (UserInfo) session.getAttribute((Constants.SESSION_USER_KEY));
        if(userInfo==null||userInfo.getId()<=0||userInfo.getUserName()==""){
            log.warn("用户未登陆");
            return false;
        }
        log.info("用户已登陆");
        return true;
    }
}
